<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px">

      <el-form-item prop="keyName">
        <el-input v-model="queryParams.keyName" placeholder="名称/联系人" clearable style="width: 240px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="状态" prop="status" style="margin-left: -30px">
        <el-select v-model="queryParams.status" placeholder="全部" clearable style="width: 240px">
          <el-option value="" label="全部"></el-option>
          <el-option v-for="item in statusType" :key="item.status" :label="item.title" :value="item.status" />
        </el-select>
      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" type="flex" justify="space-between">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['system:dict:add']">
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-dropdown trigger="click">
          <el-button type="primary" size="mini">
            导出<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="handleExport('now')">导出当前</el-dropdown-item>
            <el-dropdown-item @click.native="handleExport('all')">导出全部</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>
    </el-row>

    <el-table :row-class-name="rowStyle" :border="true" v-loading="loading" highlight-current-row
      :data="enumerationList" @selection-change="handleSelectionChange" height="calc(100vh - 250px)" :header-cell-style="{
        background: '#ebebeb'
      }">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" />
      <af-table-column label="名称" align="center" prop="name" show-overflow-tooltip />
      <af-table-column label="联系人" align="center" prop="contactName" show-overflow-tooltip />
      <af-table-column label="联系电话" align="center" prop="phone" show-overflow-tooltip />
      <af-table-column label="区域" align="center" width="180" show-overflow-tooltip>
        <template slot-scope="scope">
          <div>
            {{ scope.row.area[0] }}-{{ scope.row.area[1] }}-{{
                scope.row.area[2]
            }}
          </div>
        </template>
      </af-table-column>
      <af-table-column label="地址" align="center" prop="address" show-overflow-tooltip />
      <af-table-column label="负责人" align="center" prop="responseName" show-overflow-tooltip />
      <af-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
      <af-table-column label="状态" fixed="right" align="center" prop="status" width="120">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status == 1" active-color="#169bd5" inactive-color="#aaaaaa"
            @change="switchShowStatus(scope.row)" />
        </template>
      </af-table-column>
      <el-table-column label="操作" fixed="right" align="center" width="140" >
        <template slot-scope="scope">
          <el-button style="padding:0"  type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:dict:edit']">编辑</el-button>
          <el-button  v-if="scope.row.status === 0"   type="text" icon="el-icon-delete"
            @click="handleDelete(scope.row)" v-hasPermi="['system:dict:remove']" style="color:red;padding:0">删除</el-button>
          <el-button  v-else  style="color: #999999;padding:0" type="text" icon="el-icon-delete" disabled>删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div>
      <pagination   style="margin:0;padding: 0;" :total="total" :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize" @pagination="getList" />
    </div>


    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="联系人" prop="contactName">
          <el-input v-model="form.contactName" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入电话" />
        </el-form-item>

        <el-form-item label="区域" prop="code">
          <div class="block" style="width: 100%">
            <el-cascader v-model="form.code" placeholder="请选择区域" :options="regionValue" @change="handleChange" ref="cascader"
              style="width: 100%">
            </el-cascader>
          </div>
        </el-form-item>

        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="负责人" prop="responseName">
          <el-input v-model="form.responseName" placeholder="请输入负责人" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  outsourcers,
  outsourcersAdd,
  outsourcersUpdate,
  outsourcersEdit,
  outsourcersDel,
} from "@/api/tree/outsourcers"

import region from "@/api/tree/province.js"
import { title } from "process"
import { placeOnList } from '@/api/comprehensiveSearchManage/archive'

export default {
  name: "dictionary",
  data () {
    var validatePhone = (rules, value, callback) => {
      if (!value) {
        callback(new Error("请输入电话"))
      } else if (!value.match(/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/)) {
        callback(new Error('电话格式错误'))
      } else {
        callback()
      }
    }
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 枚举表格数据
      enumerationList: [],
      //枚举类型
      typeList: [],
      //地区
      regionValue: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        keyName: undefined,
        status: '',
      },
      statusType: [
        {
          title: '开启',
          status: 1
        },
        {
          title: '禁用',
          status: 0
        }
      ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        contactName: [
          { required: true, message: "请输入联系人", trigger: "blur" },
        ],
        phone: [{ required: true, validator: validatePhone, trigger: "blur" }],
        code: [{ required: true, message: "请选择区域", trigger: "blur" }],
        address: [{ required: true, message: "请输入地址", trigger: "blur" }],
        responseName: [
          { required: true, message: "请输入负责人", trigger: "blur" },
        ],
      },
    }
  },
  created () {
    this.regionValue = region.list
    this.getList()
  },
  methods: {
    /** 查询枚举列表 */
    getList () {
      this.loading = true
      outsourcers(this.queryParams).then((response) => {
        for (let i = 0; i < response.rows.length; i++) {
          response.rows[i].area = JSON.parse(response.rows[i].area)
          response.rows[i].code = JSON.parse(response.rows[i].code)
        }
        this.enumerationList = response.rows
        this.total = response.total
        this.loading = false
      })
    },

    handleChange (value) {
      // console.log(this.form.area)
      this.form.area = JSON.stringify(this.$refs["cascader"].getCheckedNodes()[0].pathLabels
      )
      // console.log(this.$refs["cascader"].getCheckedNodes()[0])
    },

    // 字典状态字典翻译
    statusFormat (row, column) {
      return this.selectDictLabel(this.statusOptions, row.status)
    },
    // 取消按钮
    cancel () {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset () {
      this.form = {
        pageNum: 1,
        pageSize: 20,
        keyName: undefined,
        status: undefined,
      }
      this.resetForm("form")
    },
    /** 查询按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset()
      this.open = true
      this.title = "外包商字典：新增"
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map((item) => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset()
      const Id = row.id || this.ids
      outsourcersEdit(Id).then((response) => {
        response.data.area = JSON.parse(response.data.area)
        response.data.code = JSON.parse(response.data.code)
        this.form = response.data
        this.open = true
        this.title = "外包商字典：编辑"
      })
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            this.form.area = JSON.stringify(this.form.area)
            this.form.code = JSON.stringify(this.form.code)
            outsourcersUpdate(this.form).then((response) => {
              this.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            this.form.status = 0
            // this.form.area = JSON.stringify(this.form.area)
            this.form.code = JSON.stringify(this.form.code)
            outsourcersAdd(this.form).then((response) => {
              this.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const Id = row.id || this.ids
      const name = row.name
      this.$confirm('是否确认删除名称为"' + name + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return outsourcersDel(Id)
        })
        .then(() => {
          this.getList()
          this.msgSuccess("删除成功")
        })
    },
    // /** 导出按钮操作 */
    handleExport (e) {
      var different = ''
      var params = ''
      if (e === 'now') {
        different = '当前'
        params = this.queryParams //对应接口参数
      } else if (e === 'all') {
        different = '所有'
        params = null
      } else {
        return
      }
      let that = this
      let loading
      this.$confirm('是否确认导出' + different + '数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        loading = that.$loading({
          lock: true,
          text: '导出中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        outsourcers(params).then((response) => {
          for (let i = 0; i < response.rows.length; i++) {
            response.rows[i].area = JSON.parse(response.rows[i].area)
          }
          let mydata = [
            [
              '序号',
              '名称',
              '联系人',
              '联系电话',
              '区域',
              '地址',
              '负责人',
              '备注',
              '状态',
            ],
            ...response.rows.map((item, index) => ([
              index + 1,
              item.name,
              item.contactName,
              item.phone,
              item.area[0] + '-' + item.area[1] + '-' + item.area[2],
              item.address,
              item.responseName,
              item.remark,
              item.status === 0 ? '禁用' : '开启',
            ]))
          ]
          let requireMerge = []
          that.$util.createxlsx({
            mydata,
            fileName: '外包商字典',
            dataList: response.rows,
            type: 'orderId',
            requireMerge,
            loading
          })
        })
      }).catch(function () { })
    },
    //切换状态
    switchShowStatus (row) {
      if (row.status === 1) {
        this.handleUnPublish(row)
      } else if (row.status === 0) {
        this.handlePublish(row)
      }
    },
    handlePublish (row) {
      row.area = JSON.stringify(row.area)
      row.code = JSON.stringify(row.code)
      this.$confirm('是否开启', "确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return outsourcersUpdate({
          ...row,
          status: 1
        })
      }).then(() => {
        this.getList()
        this.msgSuccess("开启成功")
      }).catch(function () {
      })
    },


    handleUnPublish (row) {
      row.area = JSON.stringify(row.area)
      row.code = JSON.stringify(row.code)
      this.$confirm('是否禁用', "确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return outsourcersUpdate({
          ...row,
          status: 0
        })
      }).then(() => {
        this.getList()
        this.msgSuccess("禁用成功")
      }).catch(function () {
      })
    },
    rowStyle ({ row }) {
      var arr = this.ids
      for (let i = 0; i < arr.length; i++) {
        if (row.id === arr[i]) {
          return "rowStyle"
        }
      }
    },
  },
  updated() {
    this.$refs["multipleTable"].doLayout();
  }
}
</script>
<style scoped>
.app-container {
  height: 85vh;
}

::v-deep .el-table__body tr.current-row>td {

  background: #a8d6fe !important;
}

::v-deep .rowStyle {
  background-color: #a8d6fe !important;
}

::v-deep .el-table__body tr:hover>td {
  background: #a8d6fe !important;
}
</style>
